import axios from 'axios'
import { Message } from 'element-ui';
let message = ''


axios.defaults.timeout = 30000
axios.defaults.baseURL = ''

axios.interceptors.request.use(
    config => {
        message.close && message.close()
        message = Message({
          dangerouslyUseHTMLString: true,
          message: '<p style="margin-left: 10px; color: #909399">Loading...</p>',
          center: true,
          iconClass: 'el-icon-loading',
          duration: 0
        })
        if(config.method == 'post') {
          if(config.url == '/v1/wechat/refund' || config.url == '/v1/upload/image') {
            return config
          }
          config.data = {
            ...config.data,
            token: localStorage.getItem('token')
          }
        } else if (config.method == 'get') {
          config.params = {
            ...config.params,
            token: localStorage.getItem('token')
          }
        }
        return config
    },
    err => {
        message.close()
        message = Message.error(err.toString())
        return Promise.reject(err)
    }
)

//http response 拦截器
axios.interceptors.response.use(
    response => {
        message.close()
        if(response.data.code !== 0) {
          message = Message.warning(response.data.data.message)
          if(response.data.code == -1) {
            localStorage.removeItem('token')
            setTimeout(() => {
              // window.location.href = '/backadmin/#/login'
            }, 1500)
          }
        }
        return response
    },
    error => {
        message.close()
        message = Message.error(error.toString())
        return Promise.reject(error)
    }
)

export default axios